import React, { useState, useEffect } from 'react'
import { List, Row , Col, Modal, message, Button } from 'antd'
import axios from 'axios'
import servicePath from '../config/baseUrl'
import '../styles/ArticleList.css'

const { confirm } = Modal

const ArticleList = (props) => {
  const [list, setList] = useState([])
  // 得到文章列表
  const getList = () => {
    axios({
      method: 'get',
      url: servicePath.getArticleList,
      withCredentials: true,
      header:{ 'Access-Control-Allow-Origin':'*' },
    }).then(resp => {
      setList(resp.data.list)
    })
  }
  // 当我们进入页面的使用，就希望可以获得博客文章的列表，所以要使用useEffect()方法来进行操作
  useEffect(() => {
    getList()
  }, [])
  // 删除文章
  const deleteArticle = id => {
    confirm({
      title: '确定要删除这篇文章吗?',
      content: '如果你点击删除，文章将不能恢复',
      onOk() {
        axios(servicePath.deleteArticle + id,{ withCredentials: true })
          .then(resp => {
            message.success('掉了一小戳头发')
            getList()
          })
      },
      onCancel() {
        message.success('辛辛苦苦写的博客干嘛想不通要删除啊 🙄')
      }
    })
  }
  // 修改文章的跳转方法
  const updateArticle = (id, checked) => {
    props.history.push('/index/add/' + id)
  }
  return (
    <div>
      <List
        header={
          <Row className="list-div">
              <Col span={8}>
                <b>标题</b>
              </Col>
              <Col span={4}>
                <b>类别</b>
              </Col>
              <Col span={4}>
                <b>发布时间</b>
              </Col>
              <Col span={4}>
                <b>浏览量</b>
              </Col>
              <Col span={4}>
                <b>操作</b>
              </Col>
            </Row>
        }
        bordered
        dataSource={list}
        renderItem={item => (
          <List.Item>
            <Row className="list-div">
              <Col span={8}>
                {item.title}
              </Col>
              <Col span={4}>
                {item.typeName}
              </Col>
              <Col span={4}>
              {item.addTime}
              </Col>
              <Col span={4}>
              {item.view_count}
              </Col>
              <Col span={4}>
                <Button
                  type="primary"
                  onClick={() => {updateArticle(item.id)}}
                >修改</Button>
                <Button
                  style={{marginLeft: '10px'}}
                  onClick={() => {deleteArticle(item.id)}}
                >删除</Button>
              </Col>
            </Row>
          </List.Item>
        )}
      />
    </div>
  )
}
export default ArticleList